package com.jie.files.controller;

import com.jie.files.entity.Files;
import com.jie.files.entity.User;
import com.jie.files.service.FilesService;
import com.sun.deploy.net.HttpResponse;
import com.sun.deploy.net.URLEncoder;
import lombok.val;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Jeson
 * @description
 * @create 2021/10/4
 * @since 1.0.0
 */
@Controller
@RequestMapping("file")
public class FilesController {

    @Autowired
    private FilesService filesService;

    @RequestMapping("showAll")
    public String showAll(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        List<Files> filesByUserId = filesService.findFilesByUserId(user.getId());
        model.addAttribute("files",filesByUserId);
        return "showAll";
    }

    /**
     * 文件上传
     * @param aaa
     * @return
     */
    @PostMapping("upload")
    public String upload(MultipartFile aaa,HttpSession session,Model model) throws IOException {
       // System.out.println(aaa.getOriginalFilename()+"12654");
        if(aaa.getOriginalFilename().equals("") && aaa.getSize()==0){
            System.out.println("执行");
            session.setAttribute("massage","文件不能为空");
            return "redirect:/file/showAll";
        }
        User user = (User) session.getAttribute("user");
        String oldFilename = aaa.getOriginalFilename();
        //获取文件后缀
        String extension="."+ FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件路径
        String newFilename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + UUID.randomUUID().toString().replace("-","")+extension;

        long size = aaa.getSize();
        //文件类型
        String contentType = aaa.getContentType();
        //处理根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
        //System.out.println(realPath);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + "/" + format;
        //System.out.println(dateDirPath);
        File dateDir=new File(dateDirPath);
        if(!dateDir.exists()){
            dateDir.mkdirs();
        }

        Files files = new Files();
        files.setExt(extension);files.setOldFileName(oldFilename);files.setNewFileName(newFilename);files.setPath("/files/"+format);
        files.setSize(Long.toString(size));files.setType(contentType);files.setUserId(user.getId());
        filesService.upload(files);

        //处理文件上传
        aaa.transferTo(new File(dateDir,newFilename));
        return "redirect:/file/showAll";
    }

    @GetMapping("download")
    public void download(String openStyle,Integer id, HttpServletResponse response) throws IOException {
        openStyle= openStyle==null?"attachment":openStyle;
        Files file = filesService.findFileById(id);

        String s = ResourceUtils.getURL("classpath:").getPath() + "/static" + file.getPath();
        FileInputStream fileInputStream = new FileInputStream(new File(s, file.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(file.getOldFileName(),"UTF-8"));
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(fileInputStream,outputStream);
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
        if(openStyle.equals("attachment")){
            filesService.addCount(file);
        }
    }

    @GetMapping("delete")
    public String delete(Integer id) throws FileNotFoundException {
        Files file = filesService.findFileById(id);

        String s = ResourceUtils.getURL("classpath:").getPath() + "/static" + file.getPath();
        File file1 = new File(s, file.getNewFileName());
        if(file1.exists()){
            file1.delete();
        }

        filesService.deleteById(id);

        return "redirect:/file/showAll";
    }
}